﻿<%@ WebHandler Language="C#" Class="RTGS.Web.ajaxhandler.usermanagement.sys_t_user_role" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using RTGS.Library;
using RTGS.Library.DataAccess.UserManagement;
using RTGS.Library.Entities.UserManagement;
using RTGS.Library.Enum;
using RTGS.Web.support;

namespace RTGS.Web.ajaxhandler.usermanagement
{

    public class sys_t_user_role : RTGS.Web.BaseHandler
    {

        private sysTUserRoleRepo userRoleDal = new sysTUserRoleRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private sysTLogRepo logDal = new sysTLogRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
        private sysTLog log = new sysTLog();

        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
    
            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context));
                 break;
                case ("getdatabyuserid"):
                    context.Response.Write(GetDataByUserId(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler

        private string Insert(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            sysTUserRole obj = new sysTUserRole();
            bool isSuccess = true;

            if (context.Request.Params["userId"] != null && context.Request.Params["userId"].ToString() != "")
            {
                string userId = context.Request.Params["userId"].ToString();


                List<sysTUserRole> list = userRoleDal.GetList();
                var query = list.Where(x => x.userId == Convert.ToInt32(userId));
                list = query.ToList();
                if (list.Count > 0)
                {
                    foreach (sysTUserRole data in list)
                    {
                        userRoleDal.Delete(data.userRoleId);
                    }
                }
            }

            if (context.Request.Params["roleId"] != null && context.Request.Params["roleId"].ToString() != "")
            {
                string [] roleId = context.Request.Params["roleId"].ToString().Split(',');
                string userId = context.Request.Params["userId"].ToString();

                //List<sysTUserRole> list = userRoleDal.GetList();
                //var query = list.Where(x=>x.userId==Convert.ToInt32(userId[0].ToString()));
                //list = query.ToList();
                //if (list.Count > 0)
                //{
                //    foreach (sysTUserRole data in list)
                //    {
                //        userRoleDal.Delete(data.userRoleId);
                //    }
                //}

                for (int i = 0; i < roleId.Length; i++)
                {
                    obj.roleId = Convert.ToInt32(roleId[i].ToString());

                    obj.userId = Convert.ToInt32(userId);
                    obj.createdDate = DateTime.Now;
                    obj.createdBy = base.UserLoggedIn;

                    isSuccess = userRoleDal.Save(obj);
                    if (!isSuccess)
                        break;

                }

                
            }


            if (isSuccess)
            {
                helper.Data = obj;
                helper.Message = "Data has been saved!";    
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Insert User Role Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = userRoleDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Insert User Role Error";
                log.logMessage = userRoleDal.GetErrorMessage();
               
            }

            log.logSource = "sys_t_role.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

      
        private string Delete(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            bool isSuccess = true;
            string[] ids = context.Request.Params["id"].Split(',');
            foreach (string id in ids)
            {
                int intID = Convert.ToInt32(id);
                
                isSuccess = userRoleDal.Delete(intID);
                if (!isSuccess) break;
            }

            if (isSuccess)
            {
                helper.IsSuccess = true;
                helper.Message = "Data has been deleted!";

                log = new sysTLog();
                log.logEvent = "Delete User Role Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = userRoleDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Delete User Role Error";
                log.logMessage = userRoleDal.GetErrorMessage();
                
                               
            }
            log.logSource = "sys_t_role.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        
        public string GetDataByUserId(HttpContext context)
        {
            sysTRoleRepo roleDal = new sysTRoleRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
            base.ProcessRequest(context);

            int userId = 0;
            if (context.Request.Params["userId"] != null)
                userId = Convert.ToInt32(context.Request.Params["userId"]);

            
            List<sysTUserRole> list = userRoleDal.GetList();
            List<sysTRole> listRole = roleDal.GetList();
            List<sysTRole> returnList = new List<sysTRole>();
            var result = list.Where(x=>x.userId==userId);
            list = result.ToList();
            result = null;
            foreach (sysTUserRole data in list)
            {
                foreach (sysTRole role in listRole)
                {
                    if (data.roleId == role.roleId)
                    {
                        sysTRole objRole = new sysTRole();
                        objRole.roleId = role.roleId;
                        objRole.roleName = role.roleName;
                        objRole.modifiedBy = role.modifiedBy;
                        objRole.modifiedDate = role.modifiedDate;
                        objRole.createdBy = role.createdBy;
                        objRole.createdDate = role.createdDate;
                        returnList.Add(objRole);
                    }
                }
            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(returnList);

        }

       

        #endregion

    }
}